# from pydispatch import dispatcher
#
# # 1. 定义接收者函数
# def my_receiver(signal, sender, **kwargs):
#     """处理接收到的信号"""
#     print(f"接收到信号: {signal}")
#     print(f"发送者: {sender}")
#     print(f"数据: {kwargs.get('data', '无数据')}")
#     print("---")
#
# # 2. 连接接收者到特定信号
# # 接收任何发送者发送的"my_signal"信号
# dispatcher.connect(my_receiver, signal="my_signal", sender=dispatcher.Any)
#
# # 3. 发送信号
# print("第一次发送信号:")
# dispatcher.send(signal="my_signal", data="Hello World")
#
# # 可以指定发送者
# my_sender = "MySenderObject"
# print("第二次发送信号:")
# dispatcher.send(signal="my_signal", sender=my_sender, data="Hello from specific sender")
#
# # 4. 断开连接
# dispatcher.disconnect(my_receiver, signal="my_signal", sender=dispatcher.Any)
#
# # 这次发送不会被接收，因为已经断开连接
# print("第三次发送信号(不会被接收):")
# dispatcher.send(signal="my_signal", data="This won't be received")

# from pydispatch import dispatcher
#
#
# class MyReceiverClass:
#     def __init__(self, name):
#         self.name = name
#         # 在初始化时连接信号
#         dispatcher.connect(self.handle_signal, signal="object_updated")
#
#     def handle_signal(self, signal, sender, **kwargs):
#         """处理信号的类方法"""
#         print(f"[{self.name}] 接收到来自 {sender} 的更新: {kwargs.get('data')}")
#
#     def cleanup(self):
#         """断开信号连接"""
#         dispatcher.disconnect(self.handle_signal, signal="object_updated")
#
#
# # 创建发送者类
# class MySenderClass:
#     def __init__(self, name):
#         self.name = name
#
#     def do_something(self, data):
#         """执行操作并发送信号"""
#         print(f"\n{self.name} 执行了操作")
#         # 发送信号，将自身作为发送者
#         dispatcher.send(signal="object_updated", sender=self, data=data)
#
#
# # 创建接收者实例
# receiver1 = MyReceiverClass("接收者1")
# # receiver2 = MyReceiverClass("接收者2")
#
# # 创建发送者实例并触发操作
# sender = MySenderClass("发送者A")
# sender.do_something("重要数据更新")
#
# # 清理
# receiver1.cleanup()
# # receiver2.cleanup()

# from pydispatch import dispatcher
#
# # 只处理来自特定发送者的特定信号
# def specific_handler(signal, sender, **kwargs):
#     print(f"特定处理器: 信号 {signal} 来自 {sender}，数据: {kwargs.get('data')}")
#
# # 处理任何发送者的"error"信号
# def error_handler(signal, sender,** kwargs):
#     print(f"错误处理器: 来自 {sender} 的错误: {kwargs.get('message')}")
#
# # 处理任何信号
# def universal_handler(signal, sender, **kwargs):
#     print(f"通用处理器: 接收到 {signal} 来自 {sender}")
#
# # 连接处理器
# dispatcher.connect(specific_handler, signal="update", sender="special_sender")
# dispatcher.connect(error_handler, signal="error", sender=dispatcher.Any)
# dispatcher.connect(universal_handler, signal=dispatcher.Any, sender=dispatcher.Any)
#
# # 发送各种信号
# print("发送特定信号:")
# dispatcher.send(signal="update", sender="special_sender", data="测试数据")
#
# print("\n发送错误信号:")
# dispatcher.send(signal="error", sender="system", message="内存不足")
#
# print("\n发送匿名信号:")
# dispatcher.send(signal="log", data="这是一条日志")  # 默认使用 Anonymous 发送者
#
# print("\n发送未处理的特定信号:")
# dispatcher.send(signal="update", sender="other_sender", data="不会被 specific_handler 处理")


from scrapy.utils import signal as _signal
from twisted.internet.defer import Deferred, react
from twisted.internet.defer import Deferred, react
from scrapy import signals


# 1. 定义异步接收器
def async_receiver1(spider, **kwargs):
    print("接收器1：开始异步操作（2秒）")
    d = Deferred()
    # 模拟2秒后完成的异步操作
    from twisted.internet import reactor
    reactor.callLater(2, d.callback, "接收器1完成")
    return d


async def async_receiver2(spider, **kwargs):
    print("接收器2：开始协程操作（1秒）")
    from twisted.internet import reactor
    d = Deferred()
    reactor.callLater(1, d.callback, None)
    await d  # 模拟异步等待
    return "接收器2完成"


def sync_receiver3(spider, **kwargs):
    print("接收器3：同步操作")
    return "接收器3完成"


# 2. 发送异步信号
def main(reactor):
    spider = type("TestSpider", (object,), {"name": "test_spider"})()

    print("发送异步信号...")
    d = _signal.send_catch_log_deferred(
        signal=signals.spider_opened,
        sender=spider,
        spider=spider
    )

    def handle_results(results):
        print("\n所有接收器完成，结果：")
        for receiver, result in results:
            print(f"- {receiver.__name__}: {result}")

    d.addCallback(handle_results)
    return d


# 启动 Twisted 反应器运行异步逻辑
react(main)
